package com.example.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.result.Result;
import com.example.common.result.YiFeiException;
import com.example.entity.hz.Messagepz;
import com.example.entity.hz.Znx;
import com.example.entity.vo.ZnxVo;
import com.example.entity.yifei.Cmsmv;
import com.example.entity.yifei.Dscma;
import com.example.entity.yifei.Messagetongzhi;
import com.example.mapper.*;
import com.example.service.ZnxService;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.example.config.WebSocketMessage.sendMessage;

/**
* @author 14501
* @description 针对表【ZNX】的数据库操作Service实现
* @createDate 2024-07-18 08:40:09
*/
@Service
public class ZnxServiceImpl extends ServiceImpl<ZnxMapper, Znx> implements ZnxService{

    @Autowired
    private DscmaMapper dscmaMapper;
    @Resource
    private MessagetongzhiMapper messagetongzhiMapper;
    @Resource
    private ZnxMapper znxMapper;
    @Resource
    private CmsmvMapper cmsmvMapper;
    @Resource
    private CmsmeMapper cmsmeMapper;
    @Resource
    private MessagepzMapper messagepzMapper;
    @Resource
    private MessageconfigurationMapper messageconfigurationMapper;


    @Override
    @Transactional
    public Result insert(List<Znx> znx) {
        System.out.println("123456"+znx);
        try{
            znx.forEach(arr -> {
                arr.setStatus(0);
                SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
                arr.setCreationTime(dateFormat.format(new Date()));
                this.znxMapper.insert(arr);
            });
//            boolean b = this.saveBatch(znx);
//            if (b){
                return Result.success("新增成功");
//            }else {
//                return Result.error("新增失败");
//            }
        }catch (Exception e){
            throw new YiFeiException(500,"站内信新增发生异常"+e.getMessage());
        }
    }

    @Override
    public Result queryList(Integer current,Integer size,String notificationCode) {
        try{
            String bm = null;
            Map<String,Object> map = new HashMap<>();
            PageHelper.startPage(current,size, "creation_time DESC");
            Cmsmv cmsmv = this.cmsmvMapper.selectOne(new QueryWrapper<Cmsmv>().eq("MV079",notificationCode));
            if (cmsmv!=null){
                bm = cmsmv.getMv004();
            }
            List<ZnxVo> znxes = this.znxMapper.queryPageZnx(notificationCode, bm);
            PageInfo<ZnxVo> znxIPage = new PageInfo<>(znxes);
            map.put("pages", znxIPage.getPages());
            map.put("total", znxIPage.getTotal());
            map.put("list", znxIPage.getList());
            return Result.success(map);
        }catch (Exception e){
            throw new YiFeiException(500,"站内信查询发生异常"+e.getMessage());
        }
    }

    @Override
    public Result update(Integer id, Integer status) {
       try{
           Znx znx = this.znxMapper.selectById(id);
           if (znx!=null){
               znx.setStatus(status);
               int update = this.znxMapper.updateById(znx);
               if (update>0){
                   return Result.success("修改状态成功");
               }
           }
           return Result.error("修改状态错误");
       }catch (Exception e){
           throw new YiFeiException(500,"站内信查询发生异常"+e.getMessage());
       }
    }

    @Override
    @Transactional
    public Result updateBath(List<Znx> znxList) {
        try{
            znxList.forEach(arr -> {
                arr.setStatus(1);
            });
            boolean b = this.updateBatchById(znxList);
            if (b){
                return Result.success();
            }
            return Result.error("一键已读错误");
        }catch (Exception e){
            throw new YiFeiException(500,"站内信一键已读发生异常"+e.getMessage());
        }
    }

    /**
     * 保存站内信 & 发送消息
     */
    @Override
    @DSTransactional
    public void saveZnxAndSendMessage(String type, String message, String titile, String code) {
        System.out.println(message);
//        ObjectMapper objectMapper = new ObjectMapper();
//        Map<String, Object> objectMap = objectMapper.readValue(jsonString, Map.class);
        Messagetongzhi one = messagetongzhiMapper.selectOne(new LambdaQueryWrapper<Messagetongzhi>().eq(Messagetongzhi::getType, type));
        if(one == null) return;
        Messagepz messagepz = this.messagepzMapper.selectOne(new LambdaQueryWrapper<Messagepz>().eq(Messagepz::getUuid, one.getId()));
        if(messagepz == null) return;

        String personnel = messagepz.getPersonnel();
        String department = messagepz.getDepartment();
        if(StringUtils.isEmpty(personnel) && StringUtils.isEmpty(department)) return;

        Set<String> personSet = new HashSet<>();
        if(StringUtils.isNotEmpty(personnel)) {
            String[] split = personnel.split(",");
            for(int i = 0; i < split.length; i++) personSet.add(split[i]);
        }
        if(StringUtils.isNotEmpty(department)) {
            String[] split = department.split(",");
            for(int i = 0; i < split.length; i++) {
                List<Dscma> dscmas = dscmaMapper.selectList(new LambdaQueryWrapper<Dscma>().eq(Dscma::getUdf01, split[i]));
                if(dscmas != null && dscmas.size() > 0) {
                    for(Dscma dscma : dscmas) personSet.add(dscma.getMa001());
                }
            }
        }
        // 用Set过滤出所有的人员
//        List<Znx> znxList = new ArrayList<>();
        List<String> personList = new ArrayList<>();
        for(String t : personSet) {
            personList.add(t);
        }

        for(String t : personList) {
            Znx znx = Znx.builder().code("").status(0).content(message).code(code)
                    .notificationCode(t).processId(null).title(titile).creationTime(TimeUtils.getFullNowTime())
                    .build();
            znxMapper.insert(znx);
//            znxList.add(znx);
        }
//        this.saveBatch(znxList);
        if(personList.size() > 0) {
            try {
                sendMessage(personList, message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    @DSTransactional
    public void saveZnxAndSendMessageBuZouPeiZhi(String person, String message, String titile, String code) {
        if(StringUtils.isEmpty(person)) return;
        Znx znx = Znx.builder().code("").status(0).content(message).code(code)
                .notificationCode(person).processId(null).title(titile).creationTime(TimeUtils.getFullNowTime())
                .build();
        znxMapper.insert(znx);
        try {
            sendMessage(person, message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateStatusByList(List<Integer> znxList) {
        Znx znx = new Znx();
        znx.setStatus(1);
        for(Integer i : znxList) {
            znx.setId(i);
            znxMapper.updateById(znx);
        }
    }

}

